<template>
  <div class="clearfix">
    <div class="head-container">
      <el-form inline>
        <el-form-item label="申请时间">
          <el-date-picker v-model="query.date" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" :default-time="['00:00:00', '23:59:59']" @change="changeDate">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.departmentCode" placeholder="执行科室" size="small" class="filter-item"
            style="width: 200px" clearable @change="searchBtn">
            <el-option v-for="(item, index) in departmentList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.exeStates" placeholder="执行状态" size="small" class="filter-item" style="width: 200px"
            clearable @change="searchBtn">
            <el-option label="执行中" :value="1"></el-option>
            <el-option label="已完成" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.patientType" placeholder="就诊类型" size="small" class="filter-item"
            style="width: 200px" clearable @change="searchBtn">
            <el-option v-for="(item, index) in typeList" :key="index" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="query.hyperbaricOxygenStates" placeholder="是否压氧治疗" size="small" class="filter-item"
            style="width: 200px" clearable @change="searchBtn">
            <el-option label="非高压氧治疗" :value="0"></el-option>
            <el-option label="高压氧治疗" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="query.patientName" placeholder="姓名/床号/住院号/门诊号" size="small" class="filter-item"
            style="width: 200px" clearable @keyup.enter.native="searchBtn" />
        </el-form-item>
        <el-form-item label="个人 ">
          <el-checkbox v-model="query.myStates" @change="searchBtn"></el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchBtn">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="reservation">预约</el-button>
        </el-form-item>
        <!-- <el-form-item v-if="batch">
          <el-button type="primary" @click="batchReservation">批量预约</el-button>
        </el-form-item> -->
        <el-form-item><el-button type="primary" @click="unReservation">取消预约</el-button></el-form-item>
        <el-form-item><el-button type="primary" @click="toRecord">预约记录</el-button></el-form-item>
        <!-- <el-form-item><el-button type="primary" @click="operatingCabin">操舱医嘱</el-button></el-form-item>
        <el-form-item><el-button type="primary" @click="toRecord(1)">知情同意书</el-button></el-form-item> -->
        <!-- <el-form-item><el-button type="primary" @click="planClick()">提取计划</el-button></el-form-item> -->
        <!-- <el-form-item>
          <el-button type="primary" @click="planClick('yuyue')"
            >一键预约</el-button
          >
        </el-form-item> -->
      </el-form>
    </div>

    <el-dialog :visible.sync="visible" width="90%">
      <div class="schedulingPage-inner">
        <schedulingPage :active-row="activeRow" :activeRow2="activeRow2"
          @operationComplete="handleOperationCompleteInParent" :timestamp="timestamp"></schedulingPage>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button
          :loading="loadingReservation"
          type="primary"
          @click="submitReservation"
          >确认</el-button
        >
        </div> -->
    </el-dialog>


    <el-dialog :visible.sync="batchVisible" width="90%">
      <div class="schedulingPage-inner">
        <BatchContextOwenr :active-row="activeRow" :activeRow2="activeRow2"
          @operationComplete="handleOperationCompleteInParent" :timestamp="timestamp" :batchData="batchData">
        </BatchContextOwenr>
      </div>
      <!-- <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="cancel">取消</el-button>
        <el-button
          :loading="loadingReservation"
          type="primary"
          @click="submitReservation"
          >确认</el-button
        >
        </div> -->
    </el-dialog>
    <OperatingCabin ref="cabinModal" />
    <InfoForm ref="informedModal" />
    <MedicalOrderPlan ref="medicalOrderPlan" @search="searchBtn2" />
  </div>
</template>

<script>
import crudDict from "@/api/system/dict";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import { getDepartment } from "@/api/treatmentProject/treatments";
import * as ajax from "@/api/treatmentProject/app.js";
import moment from "moment";
import OperatingCabin from "../modal/operatingCabin.vue";
import MedicalOrderPlan from "../modal/medicalOrderPlan.vue";
import { getEnableAdminsWithRole } from "@/api/treatment/treatment.js";
import InfoForm from "../infoForm.vue";
import schedulingPage from "../../scheduleManagement/schedulingComp/index.vue";
import BatchContextOwenr from "../../scheduleManagement/batchContextOwenr/index.vue"; // 批量预约
const defaultForm = {
  date: [],
  applyTimeBegin: "",
  applyTimeEnd: "",
  departmentCode: null,
  exeStates: null,
  patientType: null,
  hyperbaricOxygenStates: null,
  patientName: null,
  myStates: false,
};
export default {
  name: "appLeft",
  components: {
    crudOperation,
    rrOperation,
    udOperation,
    pagination,
    OperatingCabin,
    MedicalOrderPlan,
    InfoForm,
    schedulingPage,
    BatchContextOwenr
  },
  cruds() {
    return CRUD({
      title: "治疗预约",
      url: "admin/reservation/patient/list",
      crudMethod: { ...crudDict },
      optShow: {
        reset: false,
        add: true,
        edit: false,
        del: false,
        download: false,
        opts: true,
      },
      idField: "patientId",
    });
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  props: {
    selectKeys: {
      type: Array,
      default: () => []
    },
    activeRow: {
      type: Object,
      default: null,
    },
    activeRow2: {
      type: Object,
      default: null,
    },
    checkList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    count: {
      type: Array,
      default: () => {
        return [];
      },
    },
    str: {
      type: String,
      default: "",
    },
  },
  watch: {
    count: {
      handler: function () {
        if (this.checkList && this.checkList.length) {
          this.$refs.medicalOrderPlan.showModal(
            this.checkList,
            this.$props.activeRow2.treatmentName,
            this.$props.str
          );
        } else {
          this.crud.notify("请选择患者", CRUD.NOTIFICATION_TYPE.WARNING);
        }
      },
      deep: true,
    },
  },
  created() {
    this.getBus();
  },
  data() {
    return {
      batch: false, // 是否开启批量预约
      batchVisible: false, // 批量预约显示
      batchData: [],
      permission: {
        add: ["admin", "dic/add"],
        edit: ["admin", "dic/edit"],
        del: ["admin", "dic/delete"],
      },
      rules: {
        reservationTime: [
          { required: true, message: "请选择预约时间", trigger: "change" },
        ],
        reservationDepartmentCode: [
          { required: true, message: "请选择预约科室", trigger: "change" },
        ],
        reservationDoctorId: [
          { required: true, message: "请选择预约医生", trigger: "change" },
        ],
      },
      currentRow: null,
      departmentList: [],
      doctorList: [],
      typeList: [
        {
          label: "门诊",
          value: 1,
        },
        {
          label: "住院",
          value: 2,
        },
        {
          label: "其他",
          value: 3,
        },
      ],
      data: [
        {
          id: 1,
          patientName: "xxx",
          patientType: 1,
        },
      ],
      visible: false,
      loadingReservation: false,
      formData: {
        reservationTime: "",
        reservationDepartmentCode: null,
        reservationDoctorId: null,
      },
      timestamp: null,//传给组件的时间戳
    };
  },
  mounted() {
    this.getDepartmentList();
  },
  methods: {
    getBus() {
      this.$BUS.$on('batch', data => {
        this.batch = data.length > 1;
        this.batchData = data;
      });
    },
    changeDate() {
      this.crud.query.applyTimeBegin =
        this.crud.query.date && this.crud.query.date.length > 0
          ? moment(this.crud.query.date[0]).format("YYYY-MM-DD")
          : "";
      this.crud.query.applyTimeEnd =
        this.crud.query.date && this.crud.query.date.length > 0
          ? moment(this.crud.query.date[1]).format("YYYY-MM-DD")
          : "";
      // this.searchBtn();
    },
    getDepartmentList() {
      getDepartment({
        page: 1,
        size: 999,
      }).then((res) => {
        this.departmentList = res.content.map((item) => {
          return {
            label: item.departmentName,
            value: item.departmentCode,
            // value: item.hisDepartmentId,
          };
        });
      });
    },
    changeCode(val) {
      this.formData.reservationDoctorId = null;
      if (val) {
        this.getDoctorList(val);
      } else {
        this.doctorList = [];
      }
    },
    getDoctorList(val) {
      getEnableAdminsWithRole({
        departmentCode: val,
      }).then((res) => {
        this.doctorList = res.content.map((item) => {
          return {
            label: item.realname,
            value: item.aid,
          };
        });
      });
    },
    getType(val) {
      let obj = this.typeList.find((item) => {
        return item.value == val;
      });
      return obj ? obj.label : "";
    },
    searchBtn() {
      console.log(this.crud.query, "this.crud.query");

      this.$emit("changeForm", this.crud.query);
      // this.searchBtn2()
    },
    //调用排班表
    getSchedulingComp() {
      // console.log("reservation-this.$props.activeRow2",this.$props.activeRow2);
      // console.log("reservation-this.$props.activeRow", this.$props.activeRow);
      this.timestamp = moment().valueOf();
      // console.log(this.timestamp, "timestamp");

      if (this.$props.activeRow2 && this.$props.activeRow2.treatmentId) {
        this.visible = true;
        this.formData.reservationTime =
          new Date(moment(new Date()).format('YYYY-MM-DD') + ' ' + this.$props.activeRow2.adviceTime);
        let _data = this.$store.state.user.user;
        this.formData.reservationDepartmentCode =
          _data.departmentList && _data.departmentList.length > 0
            ? _data.departmentList[0].departmentCode
            : null;
        this.changeCode(this.formData.reservationDepartmentCode);
        this.formData.reservationDoctorId = _data.aid;
      } else {
        this.crud.notify("请选择治疗项目", CRUD.NOTIFICATION_TYPE.WARNING);
      }
    },
    //点击预约
    reservation() {
      if (this.$props.activeRow.newFlag) {
        this.$alert('患者是否首次接受该项治疗，如果是请签署告知书', '告知书确认', {
          confirmButtonText: '确定',
          callback: action => {
            this.getSchedulingComp();
          }
        });
      } else {
        this.getSchedulingComp();
      };
    },
    // 批量预约
    batchReservation() {
      let that = this;
      this.$alert('患者是否首次接受该项治疗，如果是请签署告知书', '告知书确认', {
        confirmButtonText: '确定',
        callback: () => {
          that.batchVisible = true;
        }
      });
    },
    //提交预约，目前该功能已经不在调用
    submitReservation() {
      this.$refs.form.validate().then(() => {
        this.loadingReservation = true;
        ajax
          .reservation({
            adviceId: this.$props.activeRow2.adviceId,
            reservationTime: Number(moment(this.formData.reservationTime).format("x")),
            reservationDepartmentCode: this.formData.reservationDepartmentCode,
            reservationDoctorId: this.formData.reservationDoctorId,
          })
          .then((res) => {
            this.crud.notify("预约成功", CRUD.NOTIFICATION_TYPE.SUCCESS);
            this.loadingReservation = false;
            this.cancel();
            // this.crud.toQuery();
            this.searchBtn2();
          })
          .catch((res) => {
            // this.crud.notify(res.msg, CRUD.NOTIFICATION_TYPE.ERROR);
            this.loadingReservation = false;
          });
      });
    },
    cancel() {
      this.visible = false;
      this.formData = {
        reservationTime: "",
        reservationDepartmentCode: null,
        reservationDoctorId: null,
      };
    },
    //取消预约
    unReservation() {
      let reservationId = this.selectKeys.map(item => item.reservationId);
      let adviceId = this.$props.activeRow2.adviceId;
      if (this.$props.activeRow2 && adviceId) {
        this.$confirm("是否确定取消预约", "确认提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          ajax
            .cancelReservation({ adviceId, reservationId })
            .then((res) => {
              this.crud.notify("取消预约成功", CRUD.NOTIFICATION_TYPE.SUCCESS);
              // this.crud.toQuery();
              this.searchBtn2();
            })
            .catch((res) => {
              this.crud.notify(res.msg, CRUD.NOTIFICATION_TYPE.ERROR);
            });
        });
      } else {
        this.crud.notify("请选择治疗项目", CRUD.NOTIFICATION_TYPE.WARNING);
      }
    },
    searchBtn2() {
      this.$emit('changeItemList', this.$props.activeRow)
    },
    //预约记录
    toRecord(type = 0) {
      if (type == 1) {
        //知情同意书
        let data = this.$props.activeRow2.treatmentInformedInfo;
        if (data) {
          this.$refs.informedModal.showModal(this.$props);
        } else {
          this.crud.notify("请选择高压氧项目", CRUD.NOTIFICATION_TYPE.WARNING);
        }
      } else {
        let info = JSON.stringify(this.$props);
        console.log(this.$props, "info");

        if (this.$props.activeRow2.reservationStates == 1) {
          this.$router.push({
            name: "AppRecord",
            query: {
              info,
            },
          });
        } else {
          this.crud.notify(
            "该治疗项目暂无预约记录",
            CRUD.NOTIFICATION_TYPE.WARNING
          );
        }
      }
    },
    //操舱医嘱
    operatingCabin() {
      let data = this.$props.activeRow2.adviceHyperbaricOxygen;
      console.log(data, "data");

      if (data) {
        this.$refs.cabinModal.showModal(this.$props);
      } else {
        this.crud.notify("请选择高压氧项目", CRUD.NOTIFICATION_TYPE.WARNING);
      }
    },
    //提取计划
    planClick(str = "") {
      this.$emit("getCheckList", str);
    },
    handleCurrentChange(val) {
      this.$emit("change", val);
    },
    // [CRUD.HOOK.afterRefresh](crud) {
    //   if (crud.data && crud.data.content && crud.data.content.length) {
    //     if (this.currentRow) {
    //       const existRow = crud.data.content.find(
    //         (row) => row.patientId === this.currentRow.patientId
    //       );
    //       if (!existRow) {
    //         this.$emit("change", crud.data.content[0]);
    //       }
    //     } else {
    //       this.$emit("change", crud.data.content[0]);
    //     }
    //   }
    // },
    //子组件传来的事件用于监控关闭dialog
    handleOperationCompleteInParent() {
      this.visible = false;
      // 在这里可以添加其他操作完成后的逻辑
      this.searchBtn2();
    }
  },
};
</script>

<style lang="scss" scoped>
/deep/.crud-opts {
  display: inline-flex;
}

.table_title {
  display: inline-block;
  line-height: 30px;
  margin: 0 10px 0 0;
  vertical-align: middle;
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}

.head-container {
  padding-bottom: 0;

  /deep/.filter-item {
    margin-bottom: 0;
  }
}

/deep/.el-dialog__body {
  padding: 0px 10px 20px;
}

.schedulePage {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0); // 初始透明
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 4000;
  transition: background-color 0.3s ease; // 背景颜色过渡效果

  .schedulingPage-inner {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
    transform: scale(0); // 初始缩放为0
    transition: transform 0.3s ease; // 缩放过渡效果
  }

}
</style>
